var express = require('express');
var router = express.Router();
const { addProduct, deleteProduct, findProduct, updateProduct } = require('../database/productModel');

// 增加
router.post('/addProduct', async function (req, res, next) {
    try {
        console.log('接收到的数据:', req.body); 
        const result = await addProduct(req.body); 
        res.send(result); 
    } catch (error) {
        console.error('增加商品时出错:', error); 
        res.status(500).send('增加商品时出错，请稍后再试。'); 
    }
});

// 删除
router.post('/deleteProduct', async function (req, res, next) {
    try {
        console.log('接收到的数据:', req.body);
        const productId = parseInt(req.body.id, 10); 
        const result = await deleteProduct(productId); 
        console.log('删除结果:', result); 
        res.send('删除成功！'); 
    } catch (error) {
        console.error('删除商品时出错:', error); 
        res.status(500).send('删除商品时出错，请稍后再试。'); 
    }
});

// 更新
router.post('/updateProduct', async function (req, res, next) {
    try {
        console.log('接收到的数据:', req.body);
        const productId = parseInt(req.body.id, 10); 
        const productData = {
            name: req.body.newname,
            price: req.body.newprice,
            description: req.body.newdescription,
            category: req.body.newcategory
        };
        const result = await updateProduct(productId, productData); 
        ressend('更新成功！');
        res.send(result); 
    } catch (error) {
        console.error('更新商品时出错:', error); 
        res.status(500).send('更新商品时出错，请稍后再试。'); 
    }
});

// 查找
router.post('/findProduct', async function (req, res, next) {
    try {
        console.log('接收到的数据:', req.body);
        const productId = parseInt(req.body.id, 10); 
        const result = await findProduct(productId);
        if (!result) {
            return res.status(404).send('未找到该商品'); 
        }
        else {
            res.send('找到了！'); 
        }
    } catch (error) {
        console.error('查找商品时出错:', error); 
        res.status(500).send('查找商品时出错，请稍后再试。'); 
    }
});

module.exports = router;